package org.drushpal.service.commands
{
	import mx.collections.ArrayCollection;
	import mx.utils.StringUtil;
	
	import org.drushpal.service.DrushService;
	import org.robotlegs.mvcs.Command;
	
	public class ListCommand extends Command
	{
		[Inject]public var drushService:DrushService;
		[Inject]public var event:DrushCommandEvent;
		override public function execute():void{
			
			drushService.projectsCollection = new ArrayCollection();
			//TODO: this should be made more elegant, but it'll work for now I suppose
			var projs:Array = event.output.split("\n\n");
			projs.pop(); //There's an extra element
			var projLen:int = projs.length;
			//loop through each project
			for(var i:int=0;i<projLen;i++){
				var availableProject:Object = new Object();				
				var props:Array = (projs[i] as String).split("\n");
				if(StringUtil.trim(props[0]) == "") props.shift(); //remove an empy first element
				var propsLen:int = props.length;
				var lastProp:String = ""//stores the name of the last property for adding extra lines to it
				//now go through each property
				for(var j:int = 0;j<propsLen;j++){
					var property:Array = (props[j] as String).split("  :  ");
					if(property.length==2){
						lastProp = StringUtil.trim(property[0]).split(" ").join("").toLowerCase();
						availableProject[lastProp] = StringUtil.trim(property[1]);
					}else if(property.length==1 && lastProp.length){
						availableProject[lastProp]+=StringUtil.trim(property[0]);
					}
				}
				drushService.projectsCollection.addItem(availableProject);
			}
			
		}
	}
}